﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
using System.Text;
//using using Phone7.Fx.Preview.Security.Cryptography;
using System.Security.Cryptography;

namespace Plugin1
{
    public partial class Page1 : Page
    {
        OpenFileDialog openfile = new OpenFileDialog();
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        string fileName = String.Empty;

        public Page1()
        {
            InitializeComponent();
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //openfile.Filter = "Jpeg Files (*.jpg)|*.jpg";//限制文件类型为图片 
            openfile.Multiselect = false; //不允许多选  
            if (openfile.ShowDialog() == true)
            {
                if (openfile.File != null)
                {
                    HttpClient client = new HttpClient(new Uri("http://10.204.13.42:10001/upload", UriKind.Absolute));
                    client.FileName = openfile.File.Name;
                    client.ConcentType = "image/jpge";
                    client.PostData = openfile.File.OpenRead();
                    client.Post();

                    //fileName = openfile.File.Name;
                    ////BitmapImage bmp = new BitmapImage();  
                    ////bmp.SetSource(openfile.File.OpenRead()); 
                    ////image1.Source = bmp; 
                    //WebClient webclient = new WebClient();
                    //Uri uri = new Uri("http://192.168.80.129:8080/upload", UriKind.RelativeOrAbsolute);
                    //webclient.OpenWriteAsync(uri, "POST", openfile.File.OpenRead());
                    //webclient.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                    //webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);

                    //webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
                }
                else
                {
                    MessageBox.Show("请选择图片！");
                }
            }
        }

        void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            return;
        }

        void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            //将图片数据流发送到服务器上

            // e.UserState - 需要上传的流（客户端流）
            Stream clientStream = e.UserState as Stream;
            // e.Result - 目标地址的流（服务端流）
            Stream serverStream = e.Result;

            //请求
            
            //组织表单数据
            StringBuilder sb = new StringBuilder();
          
            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: image/jpeg");
            sb.Append("\r\n\r\n");

            string head = sb.ToString();
            byte[] form_data = Encoding.UTF8.GetBytes(head);
            //结尾
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //文件
            Stream fileStream = clientStream;
            //post总长度
            long length = form_data.Length + fileStream.Length + foot_data.Length;

            StreamWriter sw = new StreamWriter(serverStream);
            //Stream requestStream = req.GetRequestStream();
            //发送表单参数
            sw.Write(head);
            sw.Write("\r\n--" + boundary + "--\r\n");
            sw.Close();
            ////文件内容
            //byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            //int bytesRead = 0;
            //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            //    serverStream.Write(buffer, 0, bytesRead);
            //结尾
            //serverStream.Write(foot_data, 0, foot_data.Length);
            serverStream.Close();

            //响应


            //byte[] buffer = new byte[4096];
            //int readcount = 0;
            //// clientStream.Read - 将需要上传的流读取到指定的字节数组中
            //while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0)
            //{
            //    // serverStream.Write - 将指定的字节数组写入到目标地址的流
            //    serverStream.Write(buffer, 0, readcount);
            //}
            //serverStream.Close();
            //clientStream.Close();
            clientStream.Close();
            MessageBox.Show("上传成功！");
        }

        private void jiami_Click(object sender, RoutedEventArgs e)
        {
            //密钥
            string sKey = "A3F2569DESJEIWBCJOTY45DYQWF68H1Y";
            //矢量，矢量可以为空
            string sIV = "qcDY6X+aPLw=";

            byte[] Key = Convert.FromBase64String(sKey);
            byte[]IV = Convert.FromBase64String(sIV);

            byte[] src =  Convert.FromBase64String("7OIZusSwFk39d9HclW46Gg==");

            byte[] bOut  = new byte[100000];

            DESCrytography.TripleDES(src, ref bOut, Key, false);

            string result = Convert.ToBase64String(bOut);



            ////var toEncrypt = Encoding.UTF8.GetBytes("Hi my friends ! I am safe with TripleDES :)");

            //TripleDESCryptoServiceProvider tdesAlgorithm = new TripleDESCryptoServiceProvider();
            //tdesAlgorithm.Padding

            ////// Create the encryptor
            ////ICryptoTransform encryptor = tdesAlgorithm.CreateEncryptor();
            ////var cryptedBytes = encryptor.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

            //// Create the decryptor
            //ICryptoTransform decryptor = tdesAlgorithm.CreateDecryptor();
            //var decryptedBytes = decryptor.TransformFinalBlock(cryptedBytes, 0, cryptedBytes.Length);

            //var uncryptedString = Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length);

            /*
             *     ICryptoTransform ct;
    MemoryStream ms;
    CryptoStream cs;
    byte[] byt;
    mCSP.Key = Convert.FromBase64String(sKey);
    mCSP.IV = Convert.FromBase64String(sIV);
    //指定加密的运算模式
    mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
    //获取或设置加密算法的填充模式
    mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
    ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
    byt = Encoding.UTF8.GetBytes(Value);
    ms = new MemoryStream();
    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
    cs.Write(byt, 0, byt.Length);
    cs.FlushFinalBlock();
    cs.Close();
    return Convert.ToBase64String(ms.ToArray());*/

        }
    }

}
